from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from nmj.core.constants import REGEXP_SHOW_WITH_EPISODE, REGEXP_SHOW_WITH_SEASON, \
	REGEXP_MOVIES, REGEXP_SHOW_WITH_SEASON_EPISODE
from nmj.core.main import Library
from nmj.scanners.regexp_based_scanner import RegexpBasedScanner
from nmj.scanners.tmdb import TMDbScanner
from nmj.scanners.ttvdb import TheTVDbScanner
from tempfile import NamedTemporaryFile
from threading import Thread
import datetime
import logging
import os

def __get_scanner(type):
	scanner = RegexpBasedScanner()
	scanner.add_scanner(REGEXP_SHOW_WITH_EPISODE, TheTVDbScanner())
	scanner.add_scanner(REGEXP_SHOW_WITH_SEASON_EPISODE, TheTVDbScanner())
	scanner.add_scanner(REGEXP_SHOW_WITH_SEASON, TheTVDbScanner())
	scanner.add_scanner(REGEXP_MOVIES, TMDbScanner())
	return scanner

def __get_library(directory, type):
	return Library(directory, __get_scanner(type))


def __get_directory_dict(session):
	dirs = session.setdefault("nmj_dirs", [])
	if not isinstance(dirs, list):
		dirs = []
	return dirs

def settings(request):
	dirs = __get_directory_dict(request.session)
	return render_to_response("settings.html", {"nmj_dirs":dirs})

def delete_directory(request, directory_index=None):
	dirs = __get_directory_dict(request.session)
	del dirs[int(directory_index)]
	request.session["nmj_dirs"] = dirs
	return HttpResponseRedirect('/settings')

def add_directory(request):
	directory = request.POST.get('directory', None)
	type = request.POST.get('type', None)
	if directory and type is not None:
		dirs = __get_directory_dict(request.session)
		directory_dict = {"directory" : directory, "type" : type}
		dirs.append(directory_dict)
		request.session["nmj_dirs"] = dirs
	return HttpResponseRedirect('/settings')

class Update(object):
	def __init__(self):
		self.steps = []
		self.done = False

	def add_step(self, step):
		self.steps.append(step)

	def done(self):
		self._done = True

def __get_update_steps(request):
	file_name = request.session.setdefault('update_file', None)
	steps = []
	if file_name and os.path.exists(file_name):
		steps = open(file_name).readlines()
	return steps


def update(request):
	return render_to_response("update.html", {"last_update":__get_update_steps(request)})

def do_update(tmp_file, directories):
	start_date = datetime.datetime.now()
	def callback(step):
		elapsed_time = datetime.datetime.now() - start_date
		minutes, seconds = divmod(elapsed_time.seconds, 60)
		tmp_file.write(u"[%02d:%02d] %s \n" % (minutes, seconds, step))
		tmp_file.flush()

	for directory_dict in directories:
		library = __get_library(directory_dict["directory"], directory_dict["type"])
		library.set_callback(callback)
		library.clean()
		library.update()

def update_status(request):
	steps = __get_update_steps(request)
	return HttpResponse("".join(steps))

def update_start(request):
	logging.basicConfig(filename="pynmj.log", level="DEBUG")
	tmp_file = NamedTemporaryFile(suffix="pynmj", delete=False)
	request.session["update_file"] = tmp_file.name
	thread = Thread(
		target=do_update,
		name="update_thread",
		args=[tmp_file, request.session.setdefault("nmj_dirs", {})]
	)
	thread.start()
	return HttpResponseRedirect('/update')

